package com.loiot.commons.util;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import com.loiot.commons.utils.StringUtil;
import com.loiot.commons.wechat.pojo.Oauth2AccessToken;
import com.loiot.commons.wechat.pojo.WechatLog;
import org.apache.log4j.Logger;

import com.loiot.commons.cache.CacheClient;
import com.loiot.commons.utils.HttpUtil;
import com.loiot.commons.utils.JsonUtil;
import com.loiot.commons.wechat.spring.SpringContextHolder;
import com.timeloit.pojo.MpCustomer;

/**
 * 微信工具类
 * @author sujinbo
 *
 */
public class WechatUtil {

	private static Logger log = Logger.getLogger(WechatUtil.class);
	
	public static String getAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    public static String getOAuth2AccessToken="https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
	
	/**
	 * 获取公众账号accessToken,存储到服务器缓存中,
	 * key为com.timeloit.pojo.MpCustomer.accessToken.mcId
	 * @param mcId
	 * @param appId
	 * @param appSecret
	 * @return
	 */
	public static String getAccessToken(Long mcId, String appId, String appSecret){
		CacheClient cacheClient = (CacheClient) SpringContextHolder.getBean("cacheClient");
		if(cacheClient.get(MpCustomer.class.getName()+".accessToken."+mcId)==null){
			String accessToken = getAccessToken(appId, appSecret);
			if(!accessToken.equals("")){
				cacheClient.set(MpCustomer.class.getName()+".accessToken."+mcId, accessToken, 7000);
			}
			return accessToken;
		}else{
			return cacheClient.get(MpCustomer.class.getName()+".accessToken."+mcId).toString();
		}
	}
	
	/**
	 * 获取公众账号accessToken,不存储到服务器缓存中
	 * @param appId
	 * @param appSecret
	 * @return
	 */
	public static String getAccessToken(String appId, String appSecret){
		log.info("--------------------------获取accesstoken[appid:" + appId + ",secret:" + appSecret + "]--------------------");
		System.out.println(getAccessTokenUrl.replace("APPID", appId).replace("APPSECRET", appSecret));
		String tokenStr = HttpUtil.get(getAccessTokenUrl.replace("APPID", appId).replace("APPSECRET", appSecret));
		Map<String,Object> tokenMap = JsonUtil.toObject(tokenStr, Map.class);
		if(tokenMap.get("access_token")!=null){
			return tokenMap.get("access_token").toString();
		}else{
			log.info(tokenStr);
			return "";
		}
	}


    /**
     * 通过code换取网页授权access_token
     * @param appId
     * @param appSecret
     * @param code
     * @return
     *     @see Oauth2AccessToken
     */
    public static Oauth2AccessToken getOAuth2AccessToken(String appId, String appSecret,String code)
    {
       String  url=getOAuth2AccessToken.replace("APPID",appId).replace("SECRET",appSecret).replace("CODE",code);
       String reJson=HttpUtil.get(url);
       Map<String,Object> tokenMap = JsonUtil.toObject(reJson, Map.class);
       if(tokenMap.containsKey("openid"))
       {
             Oauth2AccessToken oauth2AccessToken=new Oauth2AccessToken();
             oauth2AccessToken.setAccessToken(tokenMap.get("access_token") == null ? "" : tokenMap.get("access_token").toString());
             oauth2AccessToken.setRefreshToken(tokenMap.get("refresh_token") == null ? "" : tokenMap.get("refresh_token").toString());

             oauth2AccessToken.setOpenid(tokenMap.get("openid")==null?"":tokenMap.get("openid").toString());
             oauth2AccessToken.setScope(tokenMap.get("scope") == null ? "" : tokenMap.get("scope").toString());
           if(tokenMap.containsKey("expires_in")&&tokenMap.get("expires_in")!=null&& StringUtil.isNumeric(tokenMap.get("expires_in").toString()))
           {
               int ex=Integer.parseInt(tokenMap.get("expires_in").toString());
               Date dt=new Date();

               java.util.Calendar   c   =   java.util.Calendar.getInstance();
               c.setTime(dt);
               c.add(Calendar.SECOND, ex);

               oauth2AccessToken.setExpiresIn(c.getTime());
           }

           return  oauth2AccessToken;
       }else{
           log.debug(reJson);
           return  null;
       }
    }

	
}
